<template>
    <div class="chat-page">
        <Header />
        <div class="container">
            <!-- 未登录提示 -->
            <div v-if="!userStore.isLoggedIn" class="login-required">
                <svg-icon name="chat/login-required" class="login-icon" />
                <h3>请登录后使用聊天功能</h3>
                <p>登录后可以与经纪人在线交流或咨询房源信息</p>
                <el-button type="primary" @click="goToLogin">去登录</el-button>
            </div>
            
            <!-- 聊天容器 -->
            <div v-else class="chat-container">
                <!-- 左侧聊天列表 -->
                <div class="chat-list">
                    <div class="list-header">
                        <h3>消息列表</h3>
                    </div>
                    <div v-if="chatStore.chatList.length === 0" class="empty-list">
                        <svg-icon name="chat/empty" class="empty-icon" />
                        <p>暂无聊天记录</p>
                    </div>
                    <div v-else class="contact-list">
                        <div v-for="chat in chatStore.chatList" 
                             :key="chat.targetUserId"
                             :class="['contact-item', { active: currentChatId === chat.targetUserId }]"
                             @click="selectChat(chat.targetUserId)">
                            <div class="avatar">
                                <el-badge :value="chat.unreadCount > 0 ? chat.unreadCount : ''" :hidden="!chat.unreadCount">
                                    <img :src="chat.avatar || defaultAvatar" :alt="chat.targetUserName">
                                </el-badge>
                            </div>
                            <div class="contact-info">
                                <div class="name-time">
                                    <span class="name">{{ chat.targetUserName }}</span>
                                    <span class="time">{{ formatTime(chat.lastTime) }}</span>
                                </div>
                                <p class="last-message">{{ chat.lastMessage }}</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 右侧聊天窗口 -->
                <div class="chat-window">
                    <template v-if="currentChat">
                        <div class="chat-header">
                            <div class="user-info">
                                <h3>{{ currentChat.targetUserName }}</h3>
                                <span class="connection-status" :class="{ online: chatStore.wsConnected }">
                                    {{ chatStore.wsConnected ? '在线' : '连接中...' }}
                                </span>
                            </div>
                            <el-button 
                                type="primary" 
                                plain
                                @click="viewUserProfile(currentChat.targetUserId)"
                            >
                                查看主页
                            </el-button>
                        </div>

                        <div class="message-list" ref="messagesContainer" @scroll="handleMessagesScroll">
                            <!-- 加载更多按钮 -->
                            <div v-if="hasMoreMessages" class="load-more">
                                <div v-if="messagesLoading" class="loading-spinner">
                                    <i class="el-icon-loading"></i>
                                </div>
                                <span v-else @click="loadMoreMessages">加载更多</span>
                            </div>
                            
                            <!-- 没有更多消息提示 -->
                            <div v-else class="no-more-messages">
                                没有更多消息了
                            </div>
                            
                            <!-- 消息列表 -->
                            <div v-for="(message, index) in currentMessages" 
                                 :key="message.messageId || index"
                                 :class="['message-item', { 
                                     'self': String(message.fromUserId || '') === String(userStore.userInfo?.id || ''),
                                     'system': message.messageType === 's' || message.messageType === 'system',
                                     'error': message.messageType === 'e' || message.messageType === 'error'
                                 }]">
                                <!-- 正常消息 -->
                                <template v-if="!['s', 'system', 'e', 'error'].includes(message.messageType)">
                                    <div class="avatar">
                                        <img :src="String(message.fromUserId || '') === String(userStore.userInfo?.id || '') ? 
                                                   (userStore.userInfo?.avatar || defaultAvatar) : 
                                                   (currentChat?.avatar || defaultAvatar)" 
                                             :alt="String(message.fromUserId || '') === String(userStore.userInfo?.id || '') ? 
                                                   userStore.userInfo?.nickname || '我' : 
                                                   currentChat?.targetUserName || '对方'">
                                    </div>
                                    <div class="message-content">
                                        <!-- 文本消息 -->
                                        <div v-if="!['i', 'image', '2'].includes(message.messageType)" class="message-bubble">
                                            {{ message.content }}
                                        </div>
                                        
                                        <!-- 图片消息 -->
                                        <div v-else class="message-bubble image-bubble">
                                            <img 
                                                :src="getFullImageUrl(message.content)" 
                                                alt="图片消息" 
                                                class="message-image"
                                                @click="previewImage(getFullImageUrl(message.content))"
                                            />
                                        </div>
                                        
                                        <span class="time">{{ formatMessageTime(message.sendTime) }}</span>
                                        <span v-if="String(message.fromUserId || '') === String(userStore.userInfo?.id || '')" class="read-status">
                                            {{ message.readFlag === '1' ? '已读' : '未读' }}
                                        </span>
                                    </div>
                                </template>
                                
                                <!-- 系统消息 -->
                                <div v-else-if="message.messageType === 's' || message.messageType === 'system'" class="system-message">
                                    {{ message.content }}
                                </div>
                                
                                <!-- 错误消息 -->
                                <div v-else class="error-message">
                                    {{ message.content }}
                                </div>
                            </div>
                            
                            <!-- 加载中提示 -->
                            <div v-if="messagesLoading && !hasMoreMessages" class="loading-messages">
                                <i class="el-icon-loading"></i>
                                <span>加载中...</span>
                            </div>
                        </div>

                        <!-- 图片预览组件 -->
                        <el-image-viewer
                            v-if="previewVisible"
                            :url-list="[previewUrl]"
                            :initial-index="0"
                            @close="closePreview"
                        />

                        <div class="input-box">
                            <div class="toolbar">
                                <svg-icon name="chat/emoji" class="tool-icon" />
                                <svg-icon name="chat/image" class="tool-icon" @click="showImageUploader" />
                            </div>
                            <div class="input-area">
                                <el-input
                                    v-model="messageInput"
                                    type="textarea"
                                    :rows="3"
                                    placeholder="请输入消息"
                                    @keydown.enter.prevent="sendMessage"
                                />
                            </div>
                            <div class="actions">
                                <el-button type="primary" @click="sendMessage" :disabled="!messageInput.trim() || sendingMessage">
                                    发送
                                    <i v-if="sendingMessage" class="el-icon-loading"></i>
                                </el-button>
                            </div>
                        </div>
                    </template>

                    <div v-else class="no-chat">
                        <svg-icon name="chat/welcome" class="welcome-icon" />
                        <p>选择一个联系人开始聊天</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加图片上传对话框 -->
        <el-dialog
            v-model="imageUploaderVisible"
            title="发送图片"
            width="400px"
            destroy-on-close
        >
            <div class="image-uploader">
                <el-upload
                    class="upload-area"
                    drag
                    action="#"
                    :auto-upload="false"
                    :show-file-list="true"
                    :limit="1"
                    :on-change="handleImageChange"
                    :on-exceed="handleExceed"
                    accept="image/jpeg,image/png,image/gif"
                >
                    <div v-if="!imageFile">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">拖拽图片到此处，或 <em>点击上传</em></div>
                        <div class="el-upload__tip">只能上传 jpg/png/gif 文件，且不超过 5MB</div>
                    </div>
                    <img v-else class="preview-image" :src="imagePreview" alt="Preview" />
                </el-upload>
            </div>
            <template #footer>
                <el-button @click="cancelImageUpload">取消</el-button>
                <el-button type="primary" @click="sendImageMessage" :disabled="!imageFile">发送</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElDialog, ElImageViewer, ElUpload } from 'element-plus'
import { useChatStore } from '@/stores/chat'
import { useUserStore } from '@/stores/user'
import { getToken } from '@/utils/auth'
import { getFullImageUrl } from '@/utils/imageUrl'
import request from '@/utils/request'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'
import 'dayjs/locale/zh-cn'
import { debounce } from 'lodash-es'
import Header from '@/views/common/Header.vue'

// 配置dayjs
dayjs.extend(utc)
dayjs.extend(timezone)
dayjs.locale('zh-cn')
// 设置为中国时区
dayjs.tz.setDefault('Asia/Shanghai')

const router = useRouter()
const chatStore = useChatStore()
const userStore = useUserStore()
const route = useRoute()

const currentChatId = ref(null)
const messageInput = ref('')
const messagesContainer = ref(null)
const currentPage = ref(1)
const messagesLoading = ref(false)
const hasMoreMessages = ref(false)
const sendingMessage = ref(false)
const reconnecting = ref(false)
const scrolledToBottom = ref(true)
const imageUploaderVisible = ref(false)
const imageFile = ref(null)
const imagePreview = ref(null)
const previewVisible = ref(false)
const previewUrl = ref('')

const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
const pageSize = 20

const currentChat = computed(() => {
    if (!currentChatId.value) return null
    return chatStore.chatList.find(chat => chat.targetUserId === currentChatId.value) || {
        targetUserId: currentChatId.value,
        targetUserName: '用户'
    }
})

const currentMessages = computed(() => {
    return chatStore.messages[currentChatId.value] || []
})

onMounted(async () => {
    // 检查登录状态
    if (!userStore.isLoggedIn) {
        ElMessage.warning('请先登录后再使用聊天功能')
        return
    }

    // 添加窗口焦点事件监听
    window.addEventListener('focus', handleWindowFocus)

    // 初始化聊天列表和WebSocket连接
    try {
        console.log('开始初始化聊天...')
        
        // 先加载聊天列表
        await chatStore.initChatList()
        
        // 然后初始化WebSocket连接
        await chatStore.connectWebSocket()
        
        // 处理从房源详情页跳转过来的聊天请求
        const { agentId, targetUserId, agentName, agentAvatar, houseId, directStart, chatSuccess } = route.query
        
        // 优先使用targetUserId，如果没有则使用agentId
        const chatTargetId = targetUserId || agentId
        
        if (chatTargetId) {
            console.log('从房源详情页跳转到聊天页面，目标用户ID:', chatTargetId, '经纪人ID:', agentId)
            
            // 检查是否已有与该用户的聊天
            const existingChat = chatStore.chatList.find(chat => 
                chat.targetUserId === Number(chatTargetId) || 
                chat.targetUserId === chatTargetId ||
                (agentName && chat.targetUserName === agentName)
            )
            
            if (existingChat) {
                // 选择已存在的聊天
                selectChat(existingChat.targetUserId)
            } else {
                // 创建新的聊天会话
                try {
                    // 如果有房源ID，则准备关于房源的消息
                    let initialMessage = ''
                    if (houseId) {
                        initialMessage = `您好，我对您的房源感兴趣，想了解更多信息。`
                    } else {
                        initialMessage = '您好，我想咨询一些房产相关的问题。'
                    }
                    
                    const targetUserId = Number(chatTargetId)
                    
                    // 在本地添加聊天会话
                    chatStore.addChat({
                        targetUserId: targetUserId,
                        agentId: agentId, // 保存原始经纪人ID
                        targetUserName: agentName || '经纪人',
                        avatar: agentAvatar || defaultAvatar,
                        lastMessage: initialMessage,
                        lastTime: Date.now()
                    })
                    
                    // 选择新创建的聊天
                    selectChat(targetUserId)
                    
                    // 设置要发送的消息
                    messageInput.value = initialMessage
                    
                    // 如果是直接跳转或创建聊天成功的情况，延迟1秒后自动发送消息
                    if (directStart === 'true' || chatSuccess === 'true') {
                        setTimeout(() => {
                            sendMessage();
                        }, 1000);
                    }
                    
                    // 异步创建聊天记录
                    chatStore.createChat({
                        targetUserId: targetUserId,
                        agentId: agentId,
                        targetUserName: agentName || '经纪人',
                        avatar: agentAvatar,
                        initialMessage
                    }).catch(error => {
                        console.error('创建聊天API调用失败:', error)
                        // 即使API失败，用户依然可以发送消息
                    })
                } catch (error) {
                    console.error('创建新聊天失败:', error)
                    ElMessage.error('创建聊天失败，请稍后重试')
                }
            }
        } else if (chatStore.chatList.length > 0) {
            // 默认选择第一个聊天
            selectChat(chatStore.chatList[0].targetUserId)
        }
    } catch (error) {
        console.error('初始化聊天失败:', error)
        ElMessage.error('聊天初始化失败，请刷新页面重试')
    }
})

onUnmounted(() => {
    chatStore.closeWebSocket()
    window.removeEventListener('focus', handleWindowFocus)
})

const handleWindowFocus = () => {
    // 检查WebSocket连接状态，如果已断开则重连
    if (!chatStore.wsConnected && !reconnecting.value && userStore.isLoggedIn) {
        reconnecting.value = true
        chatStore.connectWebSocket().finally(() => {
            reconnecting.value = false
        })
    }
}

const selectChat = async (userId) => {
    // 转换为字符串进行比较，避免类型不匹配问题
    const strUserId = String(userId)
    if (String(currentChatId.value) === strUserId) return
    
    try {
        messagesLoading.value = true
        currentPage.value = 1
        currentChatId.value = userId
        
        console.log('选择聊天:', userId)
        
        // 清空消息输入
        messageInput.value = ''
        
        // 加载聊天历史
        await loadChatHistory(userId)
        
        // 标记为已读
        markAsRead(userId)
        
        // 滚动到底部
        await nextTick()
        scrollToBottom()
    } catch (error) {
        console.error('选择聊天失败:', error)
        ElMessage.error('加载聊天历史失败')
    } finally {
        messagesLoading.value = false
    }
}

const loadChatHistory = async (userId) => {
    if (!userId) {
        console.error('缺少用户ID，无法加载聊天历史')
        return { total: 0 }
    }
    
    try {
        const result = await chatStore.fetchHistoryMessages({
            targetUserId: userId,
            pageNum: currentPage.value,
            pageSize
        })
        
        // 检查返回结果是否有效
        if (!result) {
            console.warn('获取聊天历史记录返回格式异常')
            return { total: 0 }
        }
        
        hasMoreMessages.value = (result.total || 0) > currentPage.value * pageSize
        return result
    } catch (error) {
        console.error('加载聊天历史失败:', error)
        ElMessage.error('加载聊天历史失败，请稍后重试')
        return { total: 0 }
    }
}

const loadMoreMessages = async () => {
    if (messagesLoading.value || !hasMoreMessages.value) return
    
    try {
        messagesLoading.value = true
        
        // 记录当前滚动位置
        const scrollHeight = messagesContainer.value?.scrollHeight || 0
        
        // 加载上一页
        currentPage.value++
        const res = await chatStore.fetchHistoryMessages({
            targetUserId: currentChatId.value,
            pageNum: currentPage.value,
            pageSize,
            prepend: true
        })
        
        // 更新是否有更多消息
        hasMoreMessages.value = res.total > currentPage.value * pageSize
        
        // 保持滚动位置
        await nextTick()
        const newScrollHeight = messagesContainer.value?.scrollHeight || 0
        messagesContainer.value.scrollTop = newScrollHeight - scrollHeight
    } catch (error) {
        console.error('加载更多消息失败:', error)
        ElMessage.error('加载更多消息失败')
        // 回滚页码
        currentPage.value--
    } finally {
        messagesLoading.value = false
    }
}

const markAsRead = async (userId) => {
    try {
        await chatStore.markAsRead(userId)
    } catch (error) {
        console.error('标记已读失败:', error)
    }
}

const sendMessage = async () => {
    if (!messageInput.value.trim() || sendingMessage.value) return
    
    // 检查当前是否有选中的聊天
    if (!currentChatId.value) {
        ElMessage.warning('请先选择一个聊天对象')
        return
    }
    
    try {
        sendingMessage.value = true
        const messageContent = messageInput.value.trim()
        
        // 清空输入框
        messageInput.value = ''
        
        // 获取用户信息
        const userId = userStore.userInfo?.id || userStore.userInfo?.userId || 'temp_user'
        const userName = userStore.userInfo?.nickname || userStore.userInfo?.username || '我'
        
        // 生成唯一的本地消息ID
        const localMessageId = `local_${Date.now()}_${Math.random().toString(36).substring(2, 10)}`
        
        // 构建本地消息对象
        const localMessage = {
            content: messageContent,
            fromUserId: userId,
            fromUserName: userName,
            toUserId: currentChatId.value,
            messageType: 'text',
            sendTime: Date.now(),
            messageId: localMessageId,
            readFlag: '0',
            status: 'sending',
            _isLocalSent: true  // 标记为本地发送的消息
        }
        
        console.log('准备发送消息:', localMessage)
        
        // 本地立即显示消息
        if (!chatStore.messages[currentChatId.value]) {
            chatStore.messages[currentChatId.value] = []
        }
        
        // 直接添加到本地消息列表
        chatStore.messages[currentChatId.value].push(localMessage)
        
        // 更新聊天列表中的最后一条消息信息
        const chatIndex = chatStore.chatList.findIndex(chat => 
            String(chat.targetUserId) === String(currentChatId.value)
        )
        
        if (chatIndex !== -1) {
            chatStore.chatList[chatIndex].lastMessage = messageContent
            chatStore.chatList[chatIndex].lastTime = Date.now()
        }
        
        // 滚动到底部
        await nextTick()
        scrollToBottom()
        
        // 通过WebSocket发送消息，但不在本地重复添加
        try {
            // 复制一个不带本地标记的消息对象发送给服务器
            const wsMessage = { ...localMessage }
            delete wsMessage._isLocalSent
            delete wsMessage.status
            
            // 使用原始API直接发送WebSocket消息
            if (chatStore.ws && chatStore.ws.readyState === WebSocket.OPEN) {
                chatStore.ws.send(JSON.stringify(wsMessage))
                
                // 标记发送成功
                const msgIndex = chatStore.messages[currentChatId.value].findIndex(m => m.messageId === localMessageId)
                if (msgIndex !== -1) {
                    chatStore.messages[currentChatId.value][msgIndex].status = 'sent'
                }
            } else {
                throw new Error('WebSocket未连接')
            }
        } catch (wsError) {
            console.error('WebSocket发送消息失败:', wsError)
            ElMessage.error('发送消息失败，请重试')
            
            // 标记本地消息为发送失败状态
            const msgIndex = chatStore.messages[currentChatId.value].findIndex(m => m.messageId === localMessageId)
            if (msgIndex !== -1) {
                chatStore.messages[currentChatId.value][msgIndex].status = 'failed'
            }
        }
    } catch (error) {
        console.error('发送消息失败:', error)
        ElMessage.error('发送消息失败，请重试')
    } finally {
        sendingMessage.value = false
    }
}

const viewUserProfile = (userId) => {
    router.push(`/user/${userId}`)
}

const formatTime = (time) => {
    if (!time) return ''
    
    const date = dayjs(time)
    const now = dayjs()
    
    if (now.diff(date, 'day') === 0) {
        // 今天
        return date.format('HH:mm')
    } else if (now.diff(date, 'day') === 1) {
        // 昨天
        return '昨天 ' + date.format('HH:mm')
    } else if (now.diff(date, 'year') === 0) {
        // 今年
        return date.format('MM-DD HH:mm')
    } else {
        // 更早
        return date.format('YYYY-MM-DD')
    }
}

const formatMessageTime = (time) => {
    if (!time) return ''
    
    const date = dayjs(time)
    const now = dayjs()
    
    if (now.diff(date, 'day') === 0) {
        // 今天
        return date.format('HH:mm')
    } else if (now.diff(date, 'day') === 1) {
        // 昨天
        return '昨天 ' + date.format('HH:mm')
    } else if (now.diff(date, 'week') === 0) {
        // 本周内
        const weekdays = ['日', '一', '二', '三', '四', '五', '六']
        return '星期' + weekdays[date.day()]
    } else if (now.diff(date, 'year') === 0) {
        // 今年内
        return date.format('MM-DD HH:mm')
    } else {
        // 更早
        return date.format('YYYY-MM-DD HH:mm')
    }
}

const handleMessagesScroll = debounce(() => {
    if (!messagesContainer.value) return
    
    const { scrollTop, scrollHeight, clientHeight } = messagesContainer.value
    scrolledToBottom.value = scrollHeight - scrollTop - clientHeight < 50
}, 100)

const scrollToBottom = () => {
    if (!messagesContainer.value) return
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
}

watch(currentMessages, async () => {
    // 当消息变化时，如果之前是在底部，则滚动到底部
    if (scrolledToBottom.value) {
        await nextTick()
        scrollToBottom()
    }
}, { deep: true })

// 从URL参数获取经纪人信息
const initChatFromParams = async () => {
    // 检查登录状态
    if (!userStore.isLoggedIn) {
        console.warn('用户未登录，无法初始化聊天')
        return
    }
    
    const { targetUserId, targetUserName, avatar, houseId, houseTitle } = route.query
    
    if (targetUserId) {
        // 如果是从房源详情页跳转过来
        if (houseId && houseTitle) {
            // 添加到聊天列表
            await chatStore.addChat({
                targetUserId,
                targetUserName,
                avatar: avatar || defaultAvatar,
                lastMessage: `咨询房源：${houseTitle}`,
                lastTime: Date.now(),
                unreadCount: 0
            })
            
            // 自动发送房源咨询消息
            await chatStore.sendMessage({
                targetUserId,
                content: `您好，我想咨询这套房源：${houseTitle}`,
                messageType: 'text',
                houseId
            })
        }
        
        // 选择该聊天
        selectChat(targetUserId)
    }
}

// 跳转到登录页
const goToLogin = () => {
    router.push({
        path: '/login',
        query: { redirect: router.currentRoute.value.fullPath }
    })
}

const showImageUploader = () => {
    imageUploaderVisible.value = true
}

const handleImageChange = (file) => {
    imageFile.value = file.raw
    imagePreview.value = URL.createObjectURL(file.raw)
}

const handleExceed = (files) => {
    ElMessage.warning('只能上传一个文件，且不超过 5MB')
}

const cancelImageUpload = () => {
    imageUploaderVisible.value = false
    imageFile.value = null
    imagePreview.value = null
}

const sendImageMessage = async () => {
    if (!imageFile.value) {
        ElMessage.warning('请先选择一张图片')
        return
    }
    
    if (imageFile.value.size > 5 * 1024 * 1024) {
        ElMessage.warning('图片大小不能超过5MB')
        return
    }
    
    try {
        sendingMessage.value = true
        
        // 显示上传中的提示
        const loadingMsg = ElMessage({
            message: '正在上传图片...',
            duration: 0,
            type: 'info'
        })
        
        // 创建FormData用于上传图片
        const formData = new FormData()
        formData.append('file', imageFile.value)
        // 使用一个特殊的houseId标识聊天图片 - 使用-1作为特殊标识，表示聊天图片
        formData.append('houseId', '-1')
        // 设置图片类型为聊天图片
        formData.append('imageType', 'chat')
        
        // 调用原来的上传API - 避免404错误
        const uploadResult = await request({
            url: '/house/image/upload',
            method: 'post',
            data: formData,
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            timeout: 30000 // 增加超时时间到30秒
        })
        
        // 关闭上传提示
        loadingMsg.close()
        
        if (!uploadResult) {
            throw new Error('上传失败，服务器未响应')
        }
        
        if (uploadResult.code !== 200) {
            throw new Error(uploadResult.msg || '图片上传失败')
        }
        
        if (!uploadResult.data || !uploadResult.data.imageUrl) {
            throw new Error('图片URL获取失败')
        }
        
        // 获取图片URL
        const imageUrl = uploadResult.data.imageUrl
        
        // 清空图片选择
        imageUploaderVisible.value = false
        imageFile.value = null
        imagePreview.value = null
        
        // 获取用户信息
        const userId = userStore.userInfo?.id || userStore.userInfo?.userId || 'temp_user'
        const userName = userStore.userInfo?.nickname || userStore.userInfo?.username || '我'
        
        // 生成唯一的本地消息ID
        const localMessageId = `local_${Date.now()}_${Math.random().toString(36).substring(2, 10)}`
        
        // 构建本地消息对象
        const localMessage = {
            content: imageUrl, // 使用上传后的图片URL
            fromUserId: userId,
            fromUserName: userName,
            toUserId: currentChatId.value,
            messageType: 'i', // 使用'i'表示图片类型
            sendTime: Date.now(),
            messageId: localMessageId,
            readFlag: '0',
            status: 'sending',
            _isLocalSent: true,  // 标记为本地发送的消息
            imageUrl: imageUrl   // 添加图片URL字段
        }
        
        console.log('准备发送图片消息:', localMessage)
        
        // 本地立即显示消息
        if (!chatStore.messages[currentChatId.value]) {
            chatStore.messages[currentChatId.value] = []
        }
        
        // 直接添加到本地消息列表
        chatStore.messages[currentChatId.value].push(localMessage)
        
        // 更新聊天列表中的最后一条消息信息
        const chatIndex = chatStore.chatList.findIndex(chat => 
            String(chat.targetUserId) === String(currentChatId.value)
        )
        
        if (chatIndex !== -1) {
            chatStore.chatList[chatIndex].lastMessage = '[图片]'
            chatStore.chatList[chatIndex].lastTime = Date.now()
        }
        
        // 滚动到底部
        await nextTick()
        scrollToBottom()
        
        // 通过WebSocket发送消息，但不在本地重复添加
        try {
            // 复制一个不带本地标记的消息对象发送给服务器
            const wsMessage = { ...localMessage }
            delete wsMessage._isLocalSent
            delete wsMessage.status
            
            // 使用原始API直接发送WebSocket消息
            if (chatStore.ws && chatStore.ws.readyState === WebSocket.OPEN) {
                chatStore.ws.send(JSON.stringify(wsMessage))
                
                // 标记发送成功
                const msgIndex = chatStore.messages[currentChatId.value].findIndex(m => m.messageId === localMessageId)
                if (msgIndex !== -1) {
                    chatStore.messages[currentChatId.value][msgIndex].status = 'sent'
                }
            } else {
                throw new Error('WebSocket未连接')
            }
        } catch (wsError) {
            console.error('WebSocket发送消息失败:', wsError)
            ElMessage.error('发送图片失败，请重试')
            
            // 标记本地消息为发送失败状态
            const msgIndex = chatStore.messages[currentChatId.value].findIndex(m => m.messageId === localMessageId)
            if (msgIndex !== -1) {
                chatStore.messages[currentChatId.value][msgIndex].status = 'failed'
            }
        }
    } catch (error) {
        console.error('发送图片失败:', error)
        ElMessage.error('发送图片失败，请重试')
    } finally {
        sendingMessage.value = false
    }
}

// 添加图片预览相关方法
const previewImage = (url) => {
    previewUrl.value = url
    previewVisible.value = true
}

const closePreview = () => {
    previewVisible.value = false
}
</script>

<style lang="scss" scoped>
.chat-page {
    max-width: 1920px;
    margin: 0 auto;
}

.container {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 148px 15px 0px 15px;
}

.chat-container {
    display: flex;
    width: 100%;
    gap: 20px;
    height: 87vh;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    background-color: #f9f9f9;
}

.chat-list {
    width: 30%;
    border-right: 1px solid #eaeaea;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px 0 0 8px;
}

.chat-window {
    width: 70%;
    padding: 20px;
    background-color: #fff;
    border-radius: 0 8px 8px 0;
}

.list-header h3 {
    font-size: 18px;
    font-weight: bold;
    color: #4A60A1;
}

.el-button {
    background: linear-gradient(90deg, #4A60A1, #6A80C1);
    color: #fff;
    border: none;
    transition: background 0.3s ease;
}

.el-button:hover {
    background: linear-gradient(90deg, #6A80C1, #4A60A1);
}

.message-item {
    margin-bottom: 24px;
    display: flex;
    gap: 12px;
    position: relative;

    &.self {
        flex-direction: row-reverse;

        .message-bubble {
            background: #3F85FB;
            color: #fff;
            border-radius: 20px 4px 20px 20px;
        }
        
        .message-content {
            align-items: flex-end;
        }
        
        .time, .read-status {
            text-align: right;
        }
    }
    
    &:not(.self):not(.system):not(.error) {
        .message-bubble {
            background: #F5F5F5;
            color: #333;
            border-radius: 4px 20px 20px 20px;
        }
    }
    
    &.system, &.error {
        justify-content: center;
    }

    .avatar img {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        object-fit: cover;
    }

    .message-content {
        display: flex;
        flex-direction: column;
        max-width: 70%;
        
        .message-bubble {
            padding: 10px 16px;
            word-break: break-word;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
        }

        .time {
            font-size: 12px;
            color: #999;
            margin-top: 4px;
        }
        
        .read-status {
            font-size: 12px;
            color: #b0b0b0;
            margin-top: 2px;
        }
    }
    
    .system-message {
        background: #f2f6fc;
        color: #909399;
        padding: 8px 16px;
        border-radius: 16px;
        font-size: 13px;
        max-width: 80%;
        margin: 0 auto;
    }
    
    .error-message {
        background: #fef0f0;
        color: #f56c6c;
        padding: 8px 16px;
        border-radius: 16px;
        font-size: 13px;
        max-width: 80%;
        margin: 0 auto;
    }
}

.chat-list {
    border-right: 1px solid #eee;
    display: flex;
    flex-direction: column;

    .list-header {
        padding: 20px;
        border-bottom: 1px solid #eee;
        
        h3 {
            margin: 0;
            color: #2F3B59;
            font-size: 18px;
        }
    }

    .empty-list {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #999;
        
        .empty-icon {
            width: 64px;
            height: 64px;
            margin-bottom: 16px;
            color: #B7BFD9;
        }
        
        p {
            font-size: 14px;
        }
    }

    .contact-list {
        flex: 1;
        overflow-y: auto;
        height: calc(100% - 70px);

        .contact-item {
            padding: 16px;
            margin-bottom: 10px;
            display: flex;
            gap: 12px;
            cursor: pointer;
            transition: all 0.3s;
            border-bottom: 1px solid #f5f7fa;

            &:hover {
                background: #f9fafc;
            }
            
            &.active {
                background: #f0f5ff;
                border-left: 3px solid #4A60A1;
            }

            .avatar {
                img {
                    width: 48px;
                    height: 48px;
                    border-radius: 50%;
                    object-fit: cover;
                }
            }

            .contact-info {
                flex: 1;
                overflow: hidden;

                .name-time {
                    display: flex;
                    justify-content: space-between;
                    margin-bottom: 4px;

                    .name {
                        color: #2F3B59;
                        font-weight: 500;
                        max-width: 140px;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }

                    .time {
                        font-size: 12px;
                        color: #999;
                    }
                }

                .last-message {
                    color: #666;
                    font-size: 13px;
                    margin: 0;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    max-width: 200px;
                }
            }
        }
    }
}

.chat-window {
    display: flex;
    flex-direction: column;

    .chat-header {
        padding: 20px;
        border-bottom: 1px solid #eee;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .user-info {
            display: flex;
            align-items: center;
            gap: 10px;
            
            h3 {
                margin: 0;
                color: #2F3B59;
                font-size: 18px;
            }

            .connection-status {
                font-size: 13px;
                color: #909399;
                
                &.online {
                    color: #67c23a;
                }
            }
        }
    }

    .message-list {
        flex: 1;
        overflow-y: auto;
        padding: 24px;
        height: calc(100% - 200px);
        background-color: #f9f9f9;
        
        .load-more, .no-more-messages {
            text-align: center;
            padding: 10px;
            font-size: 14px;
            color: #909399;
            cursor: pointer;
            
            &:hover {
                color: #4A60A1;
            }
        }
        
        .loading-spinner, .loading-messages {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 10px;
            color: #909399;
            gap: 10px;
        }
    }

    .input-box {
        border-top: 1px solid #eee;
        padding: 16px;
        background: #fff;
        display: flex;
        flex-direction: column;

        .toolbar {
            display: flex;
            align-items: center;
            gap: 16px;
            padding: 8px 0;

            .tool-icon {
                width: 24px;
                height: 24px;
                color: #666;
                cursor: pointer;
                transition: color 0.3s;

                &:hover {
                    color: #4A60A1;
                }
            }
        }

        .input-area {
            margin: 8px 0;
            
            :deep(.el-textarea__inner) {
                resize: none;
                border-radius: 8px;
                transition: all 0.3s;
                background-color: #f9f9f9;
                
                &:focus {
                    border-color: #3F85FB;
                    box-shadow: 0 0 0 2px rgba(63, 133, 251, 0.2);
                    background-color: #fff;
                }
            }
        }

        .actions {
            display: flex;
            justify-content: flex-end;
            
            .el-button {
                border-radius: 6px;
                background: #3F85FB;
                border-color: #3F85FB;
                
                &:hover {
                    background: #2c6ad4;
                    border-color: #2c6ad4;
                }
            }
        }
    }

    .no-chat {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #999;

        .welcome-icon {
            width: 120px;
            height: 120px;
            margin-bottom: 16px;
            color: #B7BFD9;
        }
        
        p {
            font-size: 16px;
        }
    }
}

@media (max-width: 768px) {
    .chat-list {
        width: 100%;
        border-right: none;
        padding: 10px;
    }

    .chat-window {
        width: 100%;
        padding: 10px;
    }
}

.login-required {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 80px 0;
    text-align: center;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    
    .login-icon {
        width: 120px;
        height: 120px;
        margin-bottom: 24px;
        color: #4A60A1;
    }
    
    h3 {
        font-size: 22px;
        color: #333;
        margin-bottom: 12px;
    }
    
    p {
        font-size: 16px;
        color: #666;
        margin-bottom: 32px;
    }
    
    .el-button {
        padding: 12px 36px;
        font-size: 16px;
    }
}

// 添加图片消息样式
.image-bubble {
    padding: 4px !important;
    background-color: transparent !important;
    max-width: 240px;

    .message-image {
        width: 100%;
        border-radius: 8px;
        cursor: pointer;
        transition: transform 0.2s;
        
        &:hover {
            transform: scale(1.02);
        }
    }
}

.message-item.self .image-bubble {
    .message-image {
        border-radius: 8px;
    }
}

// 图片上传样式
.image-uploader {
    .upload-area {
        width: 100%;
    }
    
    .preview-image {
        width: 100%;
        max-height: 200px;
        object-fit: contain;
    }
}
</style> 